package pers.xiaojun.boot.module.system.controller.permission;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import pers.xiaojun.boot.common.pojo.CommonResult;
import pers.xiaojun.boot.module.system.controller.permission.vo.permission.AssignRoleMenuReqVO;
import pers.xiaojun.boot.module.system.controller.permission.vo.permission.AssignUserRoleReqVO;
import pers.xiaojun.boot.module.system.service.permission.PermissionService;
import pers.xiaojun.boot.web.core.annotation.AdminApi;

import java.util.List;

/**
 * 权限控制层（聚合User-Role-Menu的操作）
 *
 * @author xiaojun
 * @since 2025-10-31
 */
@Tag(name = "权限", description = "权限控制层（聚合User-Role-Menu的操作）")
@AdminApi
@RestController
@RequestMapping("/system/permission")
@RequiredArgsConstructor
public class PermissionController {

    private final PermissionService permissionService;

    @GetMapping("/role/{roleId}/menu-ids")
    @Parameter(name = "roleId", description = "角色Id", required = true)
    @Operation(summary = "获取角色拥有的菜单Id列表")
    public CommonResult<List<Long>> getMenuIdListByRoleId(@PathVariable("roleId") Long roleId) {
        return CommonResult.success(permissionService.listMenuIdsByRoleId(roleId));
    }

    @PutMapping("/role/{roleId}/assign-menu")
    @Parameter(name = "roleId", description = "角色Id", required = true)
    @Operation(summary = "赋予角色菜单")
    public CommonResult<?> assignRoleMenu(@PathVariable("roleId") Long roleId, @Valid @RequestBody AssignRoleMenuReqVO assignMenuVO) {
        assignMenuVO.setRoleId(roleId);
        permissionService.assignRoleMenu(assignMenuVO);
        return CommonResult.success();
    }

    @GetMapping("/user/{userId}/role-ids")
    @Parameter(name = "userId", description = "用户Id", required = true)
    @Operation(summary = "获取用户拥有的角色Id列表")
    public CommonResult<List<Long>> getRoleIdListByUserId(@PathVariable("userId") Long roleId) {
        return CommonResult.success(permissionService.listRoleIdsByUserId(roleId));
    }

    @PutMapping("/user/{userId}/assign-role")
    @Parameter(name = "userId", description = "用户Id", required = true)
    @Operation(summary = "赋予用户角色")
    public CommonResult<List<Long>> assignUserRole(@PathVariable("userId") Long roleId, @Valid @RequestBody AssignUserRoleReqVO assignRoleVO) {
        assignRoleVO.setUserId(roleId);
        permissionService.assignUserRole(assignRoleVO);
        return CommonResult.success();
    }


}
